#include "ET++.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "EtPeTool.h"
#include "EtPeCmdNo.h"
#include "Class.h"
#include "String.h"
#include "OrdColl.h"
#include "MenuBar.h"
#include "Window.h"
#include "CommandProcessor.h"
#include "Menu.h"

extern int gCallCount(int);

//---- EtPeTool ----------------------------------------------------------------

NewMetaImpl0(EtPeTool,Manager);

int EtPeTool::count;

EtPeTool::EtPeTool(Manager *mp, const char *n) : Manager(mp)
{
	mp->AddManager(this);

	if (count == 0)
		SetName(form("*** %s ***", n));
	else
		SetName(form("%s %d", n, count));
	count++;
	keySelectItems= 0;
}

EtPeTool::~EtPeTool()
{
	SafeDelete(keySelectItems);
}

void EtPeTool::AddKeySelectItem(VObject *vop)
{
	if (keySelectItems == 0)
		keySelectItems= new OrdCollection;
	keySelectItems->Add(vop);
}

void EtPeTool::InputKbd(Token &t)
{
	if (keySelectItems) {
		Iter next(keySelectItems);
		VObject *vop;
		while (vop= (VObject*)next()) {
			if (WantGrabKeyToken(t, vop)) {
				vop->Input(t.Pos, t, GetWindow());
				return;
			}
		}
	}
	Manager::InputKbd(t);
}

bool EtPeTool::WantGrabKeyToken(Token &t, VObject *vop)
{
	bool selectKey= t.IsAscii() && (t.Code != '\r') && (t.Code != '\n');
	return selectKey && vop->ContainsPoint(t.Pos);
}

MenuBar *EtPeTool::DoMakeMenuBar()
{
	MenuBar *mb= new MenuBar;

	//---- help menu
	Menu *m= new Menu("Help", FALSE);
	m->AppendItem("About", cABOUT);
	mb->AddMenuRight(m);

	//---- tool menu
	m= new Menu("Tool", FALSE);
	m->AppendItems(
					"Close@w",  cCLOSE,
					"Spawn",    cSPAWN,
					"Print",    cPRINT,
					"-",
					"Exit ET++PE", cEXIT,
					0);
	mb->AddMenu(m);

	//---- edit menu
	m= new Menu("Edit");
	GetCmdP()->DoCreateMenu(m);
	m->AppendItems("-",
					"Cut@x",          cCUT,
					"Copy@c",         cCOPY,
					"Paste@v",        cPASTE,
					"Clear",          cCLEAR,
					"-",
					"Select All@a",   cSELECTALL,
					0);
	mb->AddMenu(m);
		
	return mb;
}

Command *EtPeTool::DoMenuCommand(int cmd)
{
	if (cmd == cEXIT)
		gCallCount(-1);
	else
		return Manager::DoMenuCommand(cmd);
	return gNoChanges;
}

void EtPeTool::DoSetupMenu(Menu *menu)
{
	menu->EnableItems(cCLOSE, cSPAWN, 0);
	menu->EnableItem(cEXIT, gCallCount(0) > 0);
}

